package net.seabookchen.dao;

import java.util.List;

import net.seabookchen.pojo.BlogPost;
import net.seabookchen.pojo.BlogTag;

import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.Query;

public class BlogPostDao extends ObjectifyGenericDao<BlogPost> {
	private int totalSize = 0;
	
	static {
		ObjectifyService.register(BlogPost.class);
	}		

	public BlogPostDao(Class<BlogPost> clazz) {
		super(clazz);
	}
	
	public int getTotalSize() {
		if (totalSize == 0) {
			totalSize = ofy().query(BlogPost.class).count();
		}
		
		return totalSize;
	}
	
	public void addPost(BlogPost blogPost) {
		super.put(blogPost);
		this.totalSize ++;
	}
	
	public void deletePost(BlogPost blogPost) {
		super.delete(blogPost);
		if (this.totalSize > 0)
			this.totalSize --;
	}
	
	public List<BlogPost> getAllPosts() {
		Query<BlogPost> posts = ofy().query(BlogPost.class).order("-postedDate");
		return deadOrLive(posts);
	}
	
	public List<BlogPost> listLatestNewPosts(int number) {
		Query<BlogPost> posts = ofy().query(BlogPost.class).order("-postedDate").limit(number);
		return deadOrLive(posts);
	}
	
	public List<BlogPost> listLatestModifiedPosts(int number) {
		Query<BlogPost> posts = ofy().query(BlogPost.class).order("-modifiedDate").limit(number);
		return deadOrLive(posts);
	}
	
	public List<BlogPost> listMostPopularPosts(int number) { 
		Query<BlogPost> posts = ofy().query(BlogPost.class).order("-thumbsUp").limit(number);
		return deadOrLive(posts);
	}
	
	public List<BlogPost> listLeastPopularPosts(int number) { 
		Query<BlogPost> posts = ofy().query(BlogPost.class).order("-thumbsDown").limit(number);
		return deadOrLive(posts);
	}
	
	public List<BlogPost> getAllPostsByTag(BlogTag tag) {
		Query<BlogPost> posts = ofy().query(BlogPost.class).filter(
				"tags", tag);
		
		return deadOrLive(posts);
	}
	
	public List<BlogPost> listPostsFromRange(int start, int end) {
		Query<BlogPost> posts = ofy().query(BlogPost.class).order("-postedDate").offset(start).limit(end - start + 1);
		return deadOrLive(posts);
	}
	
}
